<?php

/**
 * control actions.
 *
 * @package    glcci
 * @subpackage control
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class controlActions extends sfActions
{
	protected $_date_prefixes = array(
		''
	);
	
	protected function normalize($query) {
		if(($len = strlen($query)) < 4) $portion = $query;
		else {
			$half = floor($len / 2);
			//$shift = floor($len / 4) - 1;
			$portion = substr($query, 0, -$half);
		}
		return $portion;
	}
	
	protected function fieldFormIsValid($field) {
		$is_valid = true;
		$errs = array();
		if(empty($field['field_name'])) {
			$errs[] = '<em>Field Name</em> is required.';
		}
		if(!empty($errs)) {
			array_unshift($errs, 'ERRORS:');
			$this->getUser()->setFlash('field_errs', $errs);
			$is_valid = false;
		}
		return $is_valid;
	}
	
	protected function farmFormIsValid($farm) {
		$is_valid = true;
		$errs = array();
		if(empty($farm['name'])) {
			$errs[] = '<em>Farm Name</em> is required.';
		}
		if(empty($farm['contact_fn']) || empty($farm['contact_ln'])) {
			$errs[] = '<em>First &amp; Last Name</em> are required.';
		}
		if(!empty($errs)) {
			array_unshift($errs, 'ERRORS:');
			$this->getUser()->setFlash('edit_farm_errs', $errs);
			$is_valid = false;
		}
		return $is_valid;
	}
	
	protected function newFarmFormIsValid($farm) {
		$is_valid = true;
		$errs = array();
		if(empty($farm['name'])) {
			$errs[] = '<em>Farm Name</em> is required.';
		}
		if(empty($farm['contact_fn']) || empty($farm['contact_ln'])) {
			$errs[] = '<em>First &amp; Last Name</em> are required.';
		}
		foreach($farm['field_name'] as $fi_no) {
			if(empty($fi_no)) {
				$errs[] = '<em>Field Name</em> is required for all fields.';
				break;
			}
		}
		$field_cnt = count($farm['field_name']);
		for($i = 0; $i < $field_cnt; $i++) {
			$name = strtolower($farm['field_name'][$i]);
			$year = $farm['year'][$i];
			for($j = $i + 1; $j < $field_cnt; $j++) {
				if((strtolower($farm['field_name'][$j]) == $name) && ($farm['year'][$j] == $year)) {
					$errs[] = '<em>Field Name &amp; Field Year</em> must be unique for all fields.';
					break 2;
				}
			}
		}
		if(!empty($errs)) {
			array_unshift($errs, 'ERRORS:');
			$this->getUser()->setFlash('new_farm_errs', $errs);
			$is_valid = false;
		}
		return $is_valid;
	}
	
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request) {
  	
    return sfView::SUCCESS;
  }
  
  public function executeCreateFarm(sfWebRequest $request) {
  	if($request->isMethod('POST')) {
  		$farm = $request->getPostParameters();
  		//GLCCI::dump($farm, true);
  		$sess = $this->getUser();
  		if($this->newFarmFormIsValid($farm)) {
  			$agent = new FarmAgent();
  			if(($farm_id = $agent->saveNewFarm($farm, $sess->getAttribute('user_email')))) {
  				$sess->setFlash('view_farm_msg', 'New Farm Saved Successfully.');
  				$this->redirect("@view_farm?farm_id={$farm_id}");
  			}
  			else {
  				$sess->setFlash(
  					'new_farm_errs', 
  					array(
  						'Database Error! Farm not updated. Contact administrator at ' . sfConfig::get('app_admin_email'),
  						$agent->getError()
  					)
  				);
  				$this->redirect('@create_farm');
  			}
  		} else {
  			// should restore form values at some point. for now do it with JavaScript
  			$this->redirect('@create_farm');
  		}
  	} else return sfView::SUCCESS;
  }
  
  public function executeViewFarm(sfWebRequest $request) {
  	$agent = new FarmAgent();
  	$this->fields = $agent->fetchAll($request->getParameter('farm_id'));
  	$this->forward404Unless($this->fields);
  	$this->num_fields = count($this->fields);
  	$this->farm = $this->fields[0];
  	return sfView::SUCCESS;	
  }
  
  public function executeEditFarm(sfWebRequest $request) {
  	$agent = new FarmAgent();
  	if($request->isMethod('POST')) {
  		$sess = $this->getUser();
  		$farm = $request->getPostParameters();
  		//GLCCI::dump($farm, true);
  		if($this->farmFormIsValid($farm)) {
  			if($agent->updateFarm($farm, $sess->getAttribute('user_email'))) {
	  			$sess->setFlash(
	  				'view_farm_msg',
	  				'Farm information has been successfully updated.'
	  			);
	  			$this->redirect("@view_farm?farm_id={$farm['farm_id']}");
  			} else {
  				$sess->setFlash(
  					'edit_farm_errs', 
  					array(
  						'Database Error! Farm not updated. Contact administrator at ' . sfConfig::get('app_admin_email'),
  						$agent->getError()
  					)
  				);
  				$this->redirect("@edit_farm?farm_id={$farm['farm_id']}");
  			}
  		} else {
				// relying on JavaScript, so for now no value restoration
  			$this->redirect("@edit_farm?farm_id={$farm['farm_id']}");
  		}
  	} else {
	  	$this->farm = $agent->fetchFarm($request->getParameter('farm_id'));
	  	$this->forward404Unless($this->farm);
	  	return sfView::SUCCESS;
  	}
  }
  
  public function executeEditField(sfWebRequest $request) {
    $agent = new FarmAgent();
  	if($request->isMethod('POST')) {
  		$sess = $this->getUser();
  		$field = $request->getPostParameters();
  		//GLCCI::dump($field, true);
  		if($this->fieldFormIsValid($field)) {
  			if($agent->updateField($field, $sess->getAttribute('user_email'))) {
	  			$sess->setFlash(
	  				'view_farm_msg',
	  				'Field information has been successfully updated.'
	  			);
	  			$this->redirect("@view_farm?farm_id={$field['farm_id']}");
  			} else {
  				$sess->setFlash(
  					'field_errs', 
  					array(
  						'Database Error! Field not updated. Contact administrator at ' . sfConfig::get('app_admin_email'),
  						$agent->getError()
  					)
  				);
  				$this->redirect("@edit_field?field_id={$field['field_id']}");
  			}
  		} else {
				// relying on JavaScript, so for now no value restoration
  			$this->redirect("@edit_field?field_id={$field['field_id']}");
  		}
  	} else {
	  	$this->field = $agent->fetchField($request->getParameter('field_id'));
	  	$this->forward404Unless($this->field);
	  	return sfView::SUCCESS;
  	}
  	return sfView::SUCCESS;
  }
  
  public function executeAddField(sfWebRequest $request) {
  	$this->farm_id = $request->getParameter('farm_id');
  	if($request->isMethod('POST')) {
  		$sess = $this->getUser();
  		$field = $request->getPostParameters();
  		if($this->fieldFormIsValid($field)) {
  			$agent = new FarmAgent();
	  		if($agent->saveField($field, $sess->getAttribute('user_email'))) {
	  			$sess->setFlash(
	  				'view_farm_msg',
	  				'Field added to farm successfully.'
	  			);
	  			$this->redirect("@view_farm?farm_id={$this->farm_id}");
	  		} else {
  				$sess->setFlash(
  					'field_errs',
  					array(
  						'Database Error! Field not updated. Contact administrator at ' . sfConfig::get('app_admin_email'),
  						$agent->getError()
  					)
  				);
  				$this->redirect("@add_field?farm_id={$this->farm_id}");
	  		}
  		} else {
				// relying on JavaScript, so for now no value restoration
  			$this->redirect("@add_field?farm_id={$this->farm_id}");
  		}
  	} else return sfView::SUCCESS;
  }
  
  public function executeUpdatePassword(sfWebRequest $request) {
    	if($request->isXmlHttpRequest()) {
  		sfProjectConfiguration::getActive()->loadHelpers('Partial');
  		$this->setLayout(false);
  		$dao = new DAO();
  		$user_email = rawurldecode($request->getParameter('user_email'));
  		$current_pw = rawurldecode($request->getParameter('current_pw'));
  		$new_pw = rawurldecode($request->getParameter('new_pw'));
  		$dao->query("SELECT * FROM user WHERE email='$user_email' AND password=MD5('$current_pw')");
  		if($dao->queryOK()) {
  			// change the password
  			$dao->query("UPDATE user SET password=MD5('$new_pw') WHERE email='$user_email'");
  			if($dao->UpdateOK()) $html = 'Your password has been changed successfully.';
  			else {
  				$err = $dao->getError();
  				$html = "Your password has not been changed.<br />$err";
  			}
  		} else {
  			// identity not confirmed
  			$html = 'The supplied current password is invalid!<br />Your password has not been changed.';
  		}
	  	$response = $this->getResponse();
	 		$response->addCacheControlHttpHeader('no-cache');
	  	$response->setContentType('text/html');
	  	$response->sendHttpHeaders();
	  	return $this->renderText($html);
  	} else die('JavaScript Required.');
  }
  
  public function executeSearch(sfWebRequest $request) {
  	// just get the raw DAO and do the model logic here
  	$dao = new DAO();
  	$this->query = trim($request->getParameter('q'));
  	$search_type = $request->getParameter('srch_type');
  	if(!empty($this->query) || $search_type == 'dump') { 
  		$query = $this->normalize($this->query);
  		$query = $dao->getEscapedSQLString($query);
  		if($search_type == 'dump') $query = '';
			$dao->query("
				SELECT field.*, farm.*
				FROM field
				INNER JOIN farm USING (farm_id)
				WHERE (
					LOCATE('{$query}',name) !=0
					OR LOCATE('{$query}',field_name) !=0
					OR LOCATE('{$query}',CONCAT(contact_fn,' ',contact_ln)) !=0
				)
  		");
			$this->results = array();
			if($dao->queryOK()) {
				while($row = $dao->next()) $this->results[] = $row;
				$this->msg = NULL; // not used by template
				$template = 'searchResults';
			} else if($dao->hasError()) {
				$this->msg = $dao->getError();
				$template = 'searchError';
			} else if($search_type == 'dump') {
				$this->msg = 'The database is empty.';
				$template = 'searchAlert';
			} else {
				$this->msg = "No results matched your query: {$this->query}";
				$template = 'searchAlert';
			}
  	} else {
  		$this->msg = 'The search box is empty.';
  		$template = 'searchAlert';
  	}
  	// check for Ajax request
  	if($request->isXmlHttpRequest()) {
  		sfProjectConfiguration::getActive()->loadHelpers('Partial');
  		$this->setLayout(false);
	  	$response = $this->getResponse();
	 		$response->addCacheControlHttpHeader('no-cache');
	  	$response->setContentType('text/html');
	  	$response->sendHttpHeaders();
	  	$html = get_partial($template, array('results' => $this->results, 'msg' => $this->msg));
	  	return $this->renderText($html);
  	} else $this->setTemplate($template);
  }
  
  public function executePrintView(sfWebRequest $request) {
  	$agent = new FarmAgent();
  	$this->fields = $agent->fetchAll($request->getParameter('farm_id'));
  	$this->forward404Unless($this->fields);
  	$this->num_fields = count($this->fields);
  	$this->farm = $this->fields[0];
  	return sfView::SUCCESS;	
  }
  
  public function executeAccount(sfWebRequest $request) {
  	return sfView::SUCCESS;
  }
  
}
